package com.cloudweb.oa.controller;

import cn.js.fan.db.ListResult;
import cn.js.fan.util.ErrMsgException;
import cn.js.fan.util.ResKeyException;
import cn.js.fan.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudweb.oa.utils.JarFileUtil;
import com.cloudweb.oa.utils.SpringUtil;
import com.cloudweb.oa.vo.Result;
import com.cloudwebsoft.framework.util.LogUtil;
import com.redmoon.oa.android.system.MobileAppIconConfigDb;
import com.redmoon.oa.android.system.MobileAppIconConfigMgr;
import com.redmoon.oa.basic.SelectOptionDb;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class MobileAppIconController {
    @Autowired
    private HttpServletRequest request;

    @ApiOperation(value = "创建手机端应用", notes = "创建手机端应用", httpMethod = "POST")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @PreAuthorize("hasAnyAuthority('admin')")
    @ResponseBody
    @RequestMapping(value = "/createMobileAppIcon", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;"})
    public Result<Object> createMobileAppIcon() {
        boolean re = false;
        try {
            MobileAppIconConfigMgr mr = new MobileAppIconConfigMgr();
            if (!mr.isExist(request)) {
                return new Result<>(false, "已存在,不能重复添加");
            }

            re = mr.create(request);
        } catch (ErrMsgException e) {
            return new Result<>(false, e.getMessage());
        } catch (ResKeyException e) {
            LogUtil.getLog(getClass()).error(e);
        }

        return new Result<>(re);
    }

    @ApiOperation(value = "保存手机端应用", notes = "保存手机端应用", httpMethod = "POST")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @PreAuthorize("hasAnyAuthority('admin')")
    @ResponseBody
    @RequestMapping(value = "/updateMobileAppIcon", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;"})
    public Result<Object> updateMobileAppIcon() {
        boolean re = false;
        try {
            MobileAppIconConfigMgr mr = new MobileAppIconConfigMgr();
            re = mr.save(request);
        } catch (ErrMsgException e) {
            return new Result<>(false, e.getMessage());
        } catch (ResKeyException e) {
            LogUtil.getLog(getClass()).error(e);
        }

        return new Result<>(re);
    }

    @ApiOperation(value = "删除手机端应用", notes = "删除手机端应用", httpMethod = "POST")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @PreAuthorize("hasAnyAuthority('admin')")
    @ResponseBody
    @RequestMapping(value = "/delMobileAppIcon", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;"})
    public Result<Object> delMobileAppIcon() {
        boolean re = false;
        try {
            MobileAppIconConfigMgr mr = new MobileAppIconConfigMgr();
            re = mr.delBatch(request);
        } catch (ErrMsgException e) {
            return new Result<>(false, e.getMessage());
        }
        return new Result<>(re);
    }

    @ApiOperation(value = "手机端应用列表", notes = "手机端应用列表", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "op", value = "操作", dataType = "String"),
            @ApiImplicitParam(name = "page", value = "页数", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "Integer"),
            @ApiImplicitParam(name = "what", value = "名称", dataType = "String"),
            @ApiImplicitParam(name = "type", value = "类型", dataType = "Integer"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @PreAuthorize("hasAnyAuthority('admin')")
    @ResponseBody
    @RequestMapping(value = "/listMobileAppIcon", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> listMobileAppIcon(String op, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "20") Integer pageSize, @RequestParam(defaultValue = "")String what, @RequestParam(defaultValue = "-1") Integer type) {
        JSONObject jsonObject = new JSONObject();
        MobileAppIconConfigDb mb = new MobileAppIconConfigDb();
        String sql = mb.getListSql(op, type, what);
        ListResult lr = null;
        try {
            lr = mb.listResult(sql, page, pageSize);
        } catch (ResKeyException e) {
            LogUtil.getLog(getClass()).error(e);
        }

        JSONArray ary = new JSONArray();
        SelectOptionDb selectOptionDb = new SelectOptionDb();
        long total = lr.getTotal();
        for (Object o : lr.getResult()) {
            mb = (MobileAppIconConfigDb) o;
            String name = "";
            String typeName = "";
            String imgUrl = "";
            String setTime = "";
            java.text.SimpleDateFormat f = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            int id = mb.getInt("id");
            name = mb.getString("name");
            int type2 = mb.getInt("type");
            if (type2 == 1) {
                typeName = "菜单";
            } else if (type2 == 2) {
                typeName = "流程";
            } else if (type2 == 3) {
                typeName = "模块";
            } else {
                typeName = "链接";
            }

            imgUrl = mb.getString("imgUrl");
            setTime = f.format(mb.getDate("setTime"));
            int isAdd = mb.getInt("is_add");
            int isMobileStart = mb.getInt("isMobileStart");
            String icon = mb.getString("icon");
            String appTypeName = selectOptionDb.getOptionName("app_type", mb.getString("app_type"));

            JSONObject json = new JSONObject();
            json.put("id", id);
            json.put("name", name);
            json.put("type", type2);
            json.put("typeName", typeName);
            json.put("imgUrl", imgUrl);
            json.put("setTime", setTime);
            json.put("isAdd", isAdd);
            json.put("isMobileStart", isMobileStart);
            json.put("icon", icon);
            json.put("appTypeName", appTypeName);
            json.put("orders", mb.getInt("orders"));
            ary.add(json);
        }

        jsonObject.put("total", total);
        jsonObject.put("list", ary);
        return new Result<>(jsonObject);
    }

    @ApiOperation(value = "编辑手机端应用页面", notes = "编辑手机端应用页面", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", dataType = "Long"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @PreAuthorize("hasAnyAuthority('admin')")
    @ResponseBody
    @RequestMapping(value = "/editMobileAppIconPage", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> editPage(@RequestParam Long id) {
        JSONObject jsonObject = new JSONObject();

        MobileAppIconConfigDb mobileAppIconConfigDb = new MobileAppIconConfigDb();
        mobileAppIconConfigDb = mobileAppIconConfigDb.getMobileAppIconConfigDb(id);
        if (mobileAppIconConfigDb == null) {
            return new Result<>(false, "记录不存在");
        }

        String code = "";
        String name = "";
        int type = -1;
        String imgUrl = "", icon = "";
        int isMobileStart = -1;
        int isAdd = 0;
        int orders = 0;

        code = mobileAppIconConfigDb.getString("code");
        name = mobileAppIconConfigDb.getString("name");
        type = mobileAppIconConfigDb.getInt("type");
        imgUrl = mobileAppIconConfigDb.getString("imgUrl");
        isMobileStart = mobileAppIconConfigDb.getInt("isMobileStart");
        isAdd = mobileAppIconConfigDb.getInt("is_add");
        orders = mobileAppIconConfigDb.getInt("orders");
        icon = StrUtil.getNullStr(mobileAppIconConfigDb.getString("icon"));
        String appType = StrUtil.getNullStr(mobileAppIconConfigDb.getString("app_type"));
        jsonObject.put("code", code);
        jsonObject.put("name", name);
        jsonObject.put("type", type);
        jsonObject.put("imgUrl", imgUrl);
        jsonObject.put("isMobileStart", isMobileStart);
        jsonObject.put("isAdd", isAdd);
        jsonObject.put("orders", orders);
        jsonObject.put("icon", icon);
        jsonObject.put("appType", appType);
        return new Result<>(jsonObject);
    }

    @ApiOperation(value = "获取图标", notes = "获取图标", httpMethod = "POST")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @PreAuthorize("hasAnyAuthority('admin')")
    @ResponseBody
    @RequestMapping(value = "/getMobileAppIcons", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> getIcons() {
        JarFileUtil jarFileUtil = SpringUtil.getBean(JarFileUtil.class);
        JSONArray ary = new JSONArray();
        List<String> list = new ArrayList<>();
        jarFileUtil.loadFiles("static/images/mobileAppIcons", "", list);
        for (String fileName : list) {
            if (fileName.lastIndexOf("gif") != -1 || fileName.lastIndexOf("jpg") != -1 || fileName.lastIndexOf("png") != -1 || fileName.lastIndexOf("bmp") != -1 && fileName.indexOf("face") != -1) {
                String name = fileName.substring(fileName.lastIndexOf("/") + 1);
                JSONObject json = new JSONObject();
                json.put("name", name);
                if (fileName.startsWith("static/")) {
                    fileName = fileName.substring(7);
                }
                json.put("path", fileName);
                ary.add(json);
            }
        }
        return new Result<>(ary);
    }
}
